package com.lei.study;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * curator client
 *
 * @author 伍磊
 */
public class CuratorClient {

    public static void main(String[] args) throws Exception {
        // 1 连接客户端
        CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new RetryNTimes(3, 1000));
        client.start();

        // 2 创建节点
        Stat stat = client.checkExists().forPath("/curator");
        if (null != stat) {
            System.out.println("节点已存在!");
        } else {
            client.create().withMode(CreateMode.PERSISTENT).forPath("/curator", "1".getBytes());
        }

        // 3 节点数据改变监听器
        NodeCache nodeCache = new NodeCache(client, "/curator");
        // 设置为true 表示当前已经设置值
        nodeCache.start(true);
        nodeCache.getListenable().addListener(() -> {
            System.out.println("数据改变了!");
        });

        System.in.read();

    }
}
